﻿using System;
using System.Web;
using System.Web.Security;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Domain;
using Cms.Domain.Authentication;
using Cms.Utilities;
using Cms.Web.Framework.Controls;
using iLib.Web.UI;

namespace Cms.Web.UI.Admin
{
    public partial class Default : AdminBasePage, ILoginView
    {
        private LoginPresenter _presenter;

        #region ILoginView Members

        public void DisplayErrorAndPromptForNewLogin()
        {
            if (_presenter.IsValid)
                return;
            litError.Text = _presenter.ValidationErrorMessages;
            txtUsername.Focus();
            pnlError.Visible = true;
        }


        public string Username
        {
            get { return txtUsername.Text; }
            set { txtUsername.Text = value; }
        }


        public string Password
        {
            get { return txtPassword.Text; }
            set
            {
                txtPassword.Text = value;
                ClientScriptProxy.Current.RegisterStartupScript(
                    pnlLogin,
                    GetType(),
                    "setPassword",
                    "document.getElementById('ctl00_body_txtPassword').value = '" + txtPassword.Text + "';",
                    true);
            }
        }


        public bool RememberCredentials
        {
            get { return chkRememberMe.Checked; }
            set { chkRememberMe.Checked = value; }
        }


        public void Login(Administrator administrator)
        {
            Response.Cookies.Add(new HttpCookie("FrediumRememberMeCookie")
                                     {
                                         Value = Cipher.Encrypt(txtUsername.Text + (char) 9 + txtPassword.Text),
                                         Expires =
                                             chkRememberMe.Checked
                                                 ? DateTime.Now.AddYears(1)
                                                 : DateTime.Now.AddYears(-1)
                                     });
            Response.Cookies.Add(new HttpCookie("IntroHelpIsDisplayed")
                                     {
                                         Expires = DateTime.Now.AddYears(-1),
                                         Value = string.Empty
                                     });
            PrepareLogin(administrator);
            Redirect();
        }


        public void ConfigureFirstSite(Administrator administrator)
        {
            PrepareLogin(administrator);
            Response.Redirect("ConfigureFirstSite.aspx");
        }


        public string ContextTranslationFile
        {
            get { return "Admin/Translations/Login.xml"; }
        }


        public string AutoLoginEncryptedCredentials
        {
            get { return Request.QueryString["credentials"]; }
        }


        public string SavedEncryptedCredentials
        {
            get
            {
                HttpCookie cookie = Request.Cookies["FrediumRememberMeCookie"];
                if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                    return cookie.Value;
                return null;
            }
        }


        public string RequestedDomain
        {
            get { return Request.Url.Host; }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            // If the user is already logged in, redirect to the dashboard page
            if (User.Identity.IsAuthenticated)
            {
                AuthenticatedUser user = Conversion.ToAuthenticatedUser(Page.User.Identity.Name);
                if (user.AdministratorID > 0)
                    Redirect();
            }
            _presenter = new LoginPresenter(this);
            pnlError.Visible = false;
            if (Page.IsPostBack)
                return;
            txtUsername.Focus();
            _presenter.Initialize();
        }

        protected void lbLogin_Click(object sender, EventArgs e)
        {
            _presenter.Authenticate();
        }

        private void Redirect()
        {
            string returnUrl = Request.QueryString["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl)
                && returnUrl.ToLower() != "/admin"
                && returnUrl.ToLower() != "/admin/"
                && !returnUrl.ToLower().StartsWith("/admin/default.aspx"))
            {
                Response.Redirect(returnUrl);
            }
            Response.Redirect("~/Admin/Dashboard.aspx");
        }

        private void PrepareLogin(Administrator administrator)
        {
            AuthenticatedUser user = User.Identity.IsAuthenticated
                                         ? Conversion.ToAuthenticatedUser(Page.User.Identity.Name)
                                         : new AuthenticatedUser();
            user.AdministratorID = administrator.ID;
            string username = Conversion.ToCompressedString(user);
            if (Request.QueryString["ID"] == null && String.IsNullOrEmpty(Request.QueryString["credentials"]))
            {
                IDiskAccess DiskAccess = new DiskAccess();
                DiskAccess.ClearDirectory("Admin\\Resources\\Temp\\" + administrator.ID);
            }
            FormsAuthentication.SetAuthCookie(username, false);
        }
    }
}